import json
from django import forms
from django.core.exceptions import ValidationError

from django.shortcuts import render, redirect
from django import forms

from app01 import models
from app01.utils.pagination import Pagination

from app01.utils.encrypt import md5
from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.form import BootstrapModelForm
from app01.utils.pagination import Pagination



class OrderModelForm(forms.ModelForm):


    class Meta:
        model = models.Order
        # fields = "__all__"
        # 排除 oid 订单号,让系统自动生成
        # 排除 admin 管理员, 默认使用当前登录用户为管理员
        exclude = ["id", "admin"]

        # model = models.Order
        # fields = ['oid','title','price','status']
        # # widgets = {
        # # "name": forms.TextInput(attrs={"class": "form-control", "placeholder": ""})
        # # }



def order_list(request):
    form = OrderModelForm()

    ##########################################################
    # >>>>>生成页码与搜索
    data_dict = {}
    search_data = request.GET.get('query', "")
    # title__ccontains 表示使用title作为搜索字段进行内容匹配
    if search_data:
        data_dict["title__contains"] = search_data

        # 对搜索内容进行查询,为空表示获取所有数据
    queryset = models.Order.objects.filter(**data_dict).order_by('id')

    page_object = Pagination(request, queryset, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_object.html()
    page_string = page_object.page_string

    ##########################################################
    context = {
        "queryset": page_queryset,
        "form": form,
        "page_string": page_string,
        "search_data": search_data,
    }

    return render(request, 'order_list.html', context)



from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=models.Order)
def update_id(sender, instance, **kwargs):
    if instance.id is None:
        last_id = models.Order.objects.all().order_by('id').first().id
        instance.id = last_id + 1 if last_id else 1
def order_add(request):
    """添加"""

    if request.method == "GET":
        form=OrderModelForm()
        return render(request, "order_add.html",{"form":form})

    #数据效验
    form=OrderModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/order/list")

    return render(request, "order_add.html", {"form": form})